package com.walterlife.nio;

import javax.swing.text.html.HTMLDocument;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * NIOClient
 *
 * @author zhuyuwei
 * @date 2017/4/7
 */
public class NIOClient {

    private Selector selector;

    private void connect(String ip, int port) throws Exception {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        this.selector = Selector.open();
        channel.connect(new InetSocketAddress(ip, port));
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    private void listen() throws Exception {
        while (true) {
           selector.select();
           Iterator ite = selector.selectedKeys().iterator();
           while (ite.hasNext()) {
               SelectionKey key = (SelectionKey) ite.next();
               ite.remove();
               if (key.isConnectable()) {
                   SocketChannel channel = (SocketChannel) key.channel();
                   if (channel.isConnectionPending()) {
                       channel.finishConnect();
                   }
                   channel.configureBlocking(false);
                   channel.write(ByteBuffer.wrap(new String("Hello Server").getBytes()));
                   channel.register(selector, SelectionKey.OP_READ);
               } else if (key.isReadable()) {
                   read(key);
               }
           }
        }
    }

    private void read(SelectionKey key) throws Exception {
        // 获取客户端socket channel 方便读取数据
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 将数据从channel读取到buffer中
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("client receive from server" + msg);
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
        channel.write(outBuffer);
    }

    public static void main(String[] args) throws Exception {
        NIOClient client = new NIOClient();
        client.connect("127.0.0.1", 20001);
        client.listen();
    }
}
